package org.haier.aws.utils;

import com.amazonaws.services.lambda.runtime.LambdaLogger;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.sun.istack.internal.NotNull;
import com.sun.istack.internal.Nullable;

import java.io.IOException;

/**
 * Json工具类
 * @author: SongKun
 * @date: 2021/5/13
 */
public class JsonUtils {

    private static ObjectMapper mapper = new ObjectMapper();

    static {
        // 对于空的对象转json的时候不抛出错误
        mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS,false);
        // 设置输入时忽略在json字符串中存在但在java对象实际没有的属性
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
        // 允许属性名称没有引号
        mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
        // 允许单引号
        mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
        // 设置输出时包含属性的风格
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    }


    public static String toJsonString(Object obj, @Nullable LambdaLogger logger) {
        if (obj == null) {
            return null;
        }
        String json = null;
        try {
            json = mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            if (logger != null) {
                logger.log("To JsonString Error:" + e.getMessage());
            }
        }
        return json;
    }

    public static String toJsonString(Object obj) {
        return toJsonString(obj,null);
    }


    public static <T> T parse(@NotNull String json, Class<T> clazz, @Nullable LambdaLogger logger ) {
        T t = null;
        try {
            t = mapper.readValue(json,clazz);
        } catch (IOException e) {
            if (logger != null) {
                logger.log("Parse Json Error:" + e.getMessage());
            }
        }
        return t;
    }

    public static <T> T parse(@NotNull String json, Class<T> clazz) {
        return parse(json,clazz,null);
    }

}
